<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>活动管理</el-breadcrumb-item>
    <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter='20'>
        <el-col :span='8'>
           <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserList'>
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
           </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data='userlist' border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope='scope'>
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <!-- {{scope.row}} -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 角色分配按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
               <el-button type="warning" icon="el-icon-setting" size="mini" @click="fenUsers(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
     <!-- 添加用户对话框区域 -->
    <el-dialog
    title="添加用户"
    :visible.sync="addDialogVisible"
    width="50%" @close='addDialogClosed'>
    <!-- 主体区 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClosed">
      <el-form :model="eidtForm" :rules="eidtFormRules" ref="eidtFormRef" label-width="70px">
        <el-form-item label="用户名"  >
          <el-input v-model="eidtForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="eidtForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
           <el-input v-model="eidtForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配橘色对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogUsers"
      width="50%" @close='vusoiewq'>
      <p>当亲的用户： {{fennuser.username}}</p>
      <p>当前的角色： {{fennuser.role_name}}</p>
      <p>分配新角色:
        <el-select v-model="selectValue" placeholder="请选择">
         <el-option
         v-for="item in leibiaoUser"
         :key="item.id"
         :label="item.roleName"
         :value="item.id">
         </el-option>
  </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUsers = false">取 消</el-button>
        <el-button type="primary" @click="dialogButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 数据定义区域
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cd) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cd()
      }
      cd(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cd) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cd()
      }
      cd(new Error('请输入正确的手机号'))
    }
    // 保存获取到的数据
    return {
    // 获取用户列表数据
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页现实多少条数据
        pagesize: 2
      },
      // 用户数据
      userlist: [],
      // 总共有多少条用户数据
      total: 0,
      // 控制添加用对话户框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单的验证对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用密码', trigger: 'blur' },
          { min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      eidtForm: '',
      // 修改表单的验证对象
      eidtFormRules: {
        email: [
          { required: true, message: '请输入用邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框显示与隐藏
      dialogUsers: false,
      // 显示的用户列表的数据
      fennuser: {},
      // 获取到的所有列表数据
      leibiaoUser: [],
      // 绑定到对话框上的数据
      selectValue: ''
    }
  },
  // 生命周期组件初始化区域
  created() {
    // 调用刷新重新获取页面
    this.getUserList()
  },
  // 事件添加区域
  methods: {
    // 刷新重新获取页面
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 监听pagination 改变事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听switch 用户状态开关状态
    async userStateChanged(userinfo) {
      // console.log(userinfo);
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 刷新页面
        this.getUserList()
      })
    },
    // 点击按钮  弹出修改用户对话框区域
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('查询用户信息失败')
      }
      this.eidtForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改对话框关闭事件
    editDialogClosed() {
      this.$refs.eidtFormRef.resetFields()
    },
    // 点击按钮 修改用户
    editUserInfo(id) {
      this.$refs.eidtFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息请求
        const { data: res } = await this.$http.put('users/' + this.eidtForm.id, {
          email: this.eidtForm.email,
          mobile: this.eidtForm.mobile
        })
        if (res.meta.status !== 200) {
          this.$message.error('修改用户数据失败')
        }
        this.$message.success('修改用户数据成功')
        // 隐藏对话框
        this.editDialogVisible = false
        // 刷新页面
        this.getUserList()
      })
    },
    // 点击按钮 弹出删除用户对话框区域
    async removeUserById(id) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 确认删除用户 发起请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      // 刷新页面
      this.getUserList()
    },
    // 点击按钮 分配角色
    async fenUsers(user) {
      // console.log(1)
      this.fennuser = user
      // 发起网络请求
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.leibiaoUser = res.data
      // console.log(this.leibiaoUser)
      this.dialogUsers = true
    },
    // 点击确定上传数据
    async dialogButton() {
      if (!this.selectValue) {
        return this.$message.error('请选择角色')
      }
      const { data: res } = await this.$http.put(`users/${this.fennuser.id}/role`, {
        rid: this.selectValue
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.dialogUsers = false
      this.getUserList()
    },
    vusoiewq() {
      // console.log(1)
      this.selectValue = ''
      this.fennuser = {}
    }
  }

}
</script>

<style lang="less" scoped>
.el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15)!important;
}
</style>
